package com.inspectortime.webapp.inspector.fee;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.inspectortime.domain.InspectorCompany;
import com.inspectortime.domain.OptionalService;
import com.inspectortime.domain.User;
import com.inspectortime.repository.Repository;
import com.inspectortime.webapp.util.HttpSessionUtils;

public class OptionalServiceDeleteController extends AbstractController {
	
	private static Log log = LogFactory.getLog(OptionalServiceDeleteController.class);
	
	private Repository repository;
	private String successView;


	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		ModelAndView mv = null;
		OptionalService service = null;
		
		String optionalServiceId = request.getParameter("id");
		User user = HttpSessionUtils.retrieveLoggedInUser(request, repository);
		InspectorCompany company = HttpSessionUtils.retrieveLoggedInCompany(request, repository);
		
		service = company.findOptionalServiceById(optionalServiceId);

		//This shouldn't ever happen
		if (service == null) {
			throw new Exception("Tried to retrieve a non-existent optionalService for deletion.\nId: " + optionalServiceId +
								"\nUserId: " + user.getId());
		}
		
		service.setCompany(null);
		company.removeOptionalService(optionalServiceId);
		company.save();
		
		mv = new ModelAndView(this.successView);

		return mv;
	}
	
	public void setRepository(Repository repository) {
		this.repository = repository;
	}

	public void setSuccessView(String successView) {
		this.successView = successView;
	}
	



	
}
